package com.google.pvacameras.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
/**
 * This servlet handles deliver's the item information selected by the user from selection.html, and then generate 
 * the item detail page based off this information.
 * 
 * Velocity Templates are used for rendering the item details page.
 * 
 * @author David Peng (gpeng@google.com)
 * 
 */
public class ItemServlet extends HttpServlet {
	private static final long serialVersionUID = 2185743230495195782L;

	/**
	 * Get handler forwards request to post handler.
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		doPost(req, resp);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException {
		try{
		// Get post parameters
		String name = req.getParameter("itemName");
		String description = req.getParameter("itemDescription");
		String unitprice = req.getParameter("itemPrice");
		String quantity = req.getParameter("itemQuantity");
		String image = req.getParameter("itemImage");
		// So we don't write to velocity.log
		Velocity.setProperty("runtime.log.logsystem.class",
				"org.apache.velocity.runtime.log.NullLogChute");

		// Escape HTML
		Velocity.setProperty("eventhandler.referenceinsertion.class",
				"org.apache.velocity.app.event.implement.EscapeHtmlReference");
		Velocity.setProperty("eventhandler.escape.html.match", "/.*/");

		// Initialize Velocity Templates
		Velocity.init();
		VelocityContext context = new VelocityContext();

		// Get the response output stream PrintWriter
		PrintWriter pw;
		pw = resp.getWriter();

		// Injects the information from the masked Wallet Response, change Wallet
		// and the
		// FullWalletRequest JWT into
		// the template
		context.put("itemName",name);
		context.put("itemDescription",description);
		context.put("itemQuantity",quantity);
		context.put("itemPrice",unitprice);
		context.put("itemImage",image);
		// Render the template and output to print stream
		Velocity.mergeTemplate("item.vm", "UTF-8", context, pw);
		pw.flush();
		pw.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
